// 定义网络图转base64的方法
function getBase64(url, ext, callback) {
  return new Promise((resolve, reject) => {
    var canvas = document.createElement("canvas");   //创建canvas DOM元素
    var ctx = canvas.getContext("2d");
    var img = new Image;
    img.crossOrigin = 'Anonymous';
    img.src = url;
    img.onload = function () {
      canvas.width = img.width; //指定画板的宽度，自定义
      canvas.height = img.height; //指定画板的高度,自定义
      ctx.drawImage(img, 0, 0, img.width, img.height); //参数可自定义
      let dataURL = canvas.toDataURL("image/" + ext);
      canvas = null;
      resolve(dataURL)
    };
  })
}

// 定义base64转文件流的方法
function dataURLtoBlob(dataurl) {
  return new Promise((resolve, reject) => {
    let arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    resolve(new Blob([u8arr], {type: mime}))
  })
}

//将blob转换为file
function blobToFile(theBlob, fileName) {
  theBlob.lastModifiedDate = new Date();
  theBlob.name = fileName;
  return theBlob;
}

// 正则处理赋值内容
function matchStr(html, newHtml = '') {
  let relImg = /<img[\s\S]*?src\s*=\s*[\"|\'](.*?)[\"|\'][\s\S]*?>/
  let matchObj = html.match(relImg)


  if (!matchObj) return newHtml
  else {
    let startIndex = matchObj.index
    let endIndex = matchObj.index + matchObj[0].length

    let startString = html.substring(0, startIndex)
    let endString = html.substring(endIndex)


    if (matchObj[0].indexOf('dictionaries_url') === -1) {

      let htmlStr = `<div contenteditable="false">
                        <div class="pgc-image pgc-card-fixWidth">
                          <div class="pgc-img-wrapper">
                          <img src=""  dictionaries_url="${matchObj[1]}">
                              <div class="editor-image-menu">
                              <div class="editor-image-menu-bg"></div>
                              <div class="image-menu-event-prevent" style="display: none"><a class="editor-image-menu-item ">编辑</a></div>
                            </div>
                            <span class="ttcore-remove-blot"></span>
                           </div>
                           <div class="pgc-img-caption-wrapper">
                             <input  class="pgc-img-caption-ipt" type="text" placeholder="请输入图片描述(最多50字)" value="">
                             <span class="pgc-img-caption-tip ">0/ 50</span><p class="pgc-img-caption"></p>
                           </div>
                          </div>
       </div> `

      newHtml += startString + htmlStr
      return matchStr(endString, newHtml)

    } else {
      return matchStr(endString, newHtml)
    }
  }
}

// 创建自定义的图片文本格式
function newImgEl(el,status) {
  console.log(el);
  let img
  if(el.tagName === "IMG"){
    img = el
  }else{
    img = el.querySelector('img')
  }

  let src = img.src,
      text,
      add = false

  if(el.children && el.children.length){
    text = (el.children[1] && el.children[1].innerText) || ''

    if(el.children.length > 2 || text.length > 50){
      add = true
      text = ''
    }
  }

  console.log(src,status);
  let addImg = document.createElement('div')
  addImg.innerHTML = `<div class="pgc-image pgc-card-fixWidth">
                              <div class="pgc-img-wrapper">
                              <img src="${status && src}"  dictionaries_url="${src}">
                                  <div class="editor-image-menu" style="display: ${(status && 'block') || 'none'};">
                                  <div class="editor-image-menu-bg"></div>
                                  <div class="image-menu-event-prevent" ><a class="editor-image-menu-item ">编辑</a></div>
                                </div>
                                <span class="ttcore-remove-blot"></span>
                               </div>
                               <div class="pgc-img-caption-wrapper">
                             <input maxlength="50"  class="pgc-img-caption-ipt" type="text" placeholder="请输入图片描述(最多50字)" value="${text || ''}">
                             <span class="pgc-img-caption-tip ">最多50字</span><p class="pgc-img-caption">${text || ''}</p>
                           </div>
                              </div>`

  let addDiv

  if(add){
    addDiv = document.createElement('div')
    addDiv.innerHTML = addImg.innerHTML

    for(let i = 0; i < el.children.length; i++){
      if(Number(i)!==0){
        let val  = el.children[i]
        addDiv.appendChild(val)
      }
    }
  }

  return add ? addDiv : addImg
}

function matchImg11(content, el = false) {

  let div
  if (el) div = el
  else {
    div = document.createElement('div')
    div.className = "tempDiv"
    div.innerHTML = content
  }
  let imgs = div.querySelectorAll(' img')
  console.log(imgs.length)


    div.replaceChild(newImgEl(imgs[0].src,''),imgs[0])

  return div.innerHTML
}

function isNeedImg(node){
  console.log(node);
  let status = true

  if(node.tagName === 'IMG'){
    [...node.attributes].forEach(function (attr) {
      // console.log(attr.name, attr.value);
      if(attr.name === 'data-w-e'){
        node.className ='face-img'
        status = false;
        return status;
      }
    })
    console.log(46456,node.className);
  }

  return status;
}

// dom处理粘贴各种数据 解析所有网站文章的格式
function matchImg(content, el = false) {

  // 创建一个容器 用于dom操作解析
  let div
  if (el) div = el
  else {
    div = document.createElement('div')
    div.innerHTML = content
  }
  // 解析所有dom节点
  for (let item of div.children) {
    // console.log(item.className);
    // 如果只有一层img,直接替换
    if (item.tagName === "IMG" && isNeedImg(item)) {
      let whiteListIndex = whiteList.findIndex((val) => {
        return item.src.indexOf(val) !== -1
      })

      if (Number(whiteListIndex) !== -1) {
        div.replaceChild(newImgEl(item,true), item)
        continue
      }

      div.replaceChild(newImgEl(item), item)
    } else {

      // 根据每个dom节点的图片数量 进行相关逻辑解析
      let imgArr = item.querySelectorAll('img')

      // div  只有一张图时 进行处理
      if (imgArr.length === 1) {
        // console.log('找到图片');
        let whiteListIndex = whiteList.findIndex((val) => {
          return imgArr[0].src.indexOf(val) !== -1
        })
        // console.log(imgArr[0].className);
        if (Number(whiteListIndex) !== -1 && isNeedImg(imgArr[0])) {
          div.replaceChild(newImgEl(item,true), item);
          continue
        }
        if(isNeedImg(imgArr[0])){
          div.replaceChild(newImgEl(item), item)

        }
      } else if (imgArr.length > 1) {
        matchImg('', item)
      }
    }
  }

  div.innerHTML += '<br>'
  // console.log(div.innerHTML);
  return div.innerHTML
}

// 上传图片封装
async function  updateImg (base64,el,progress) {
  // let response = await instance.post('cms/commons/UploadFile')
  //
  // response = response.data
  //
  // let data = response.data.postObject
  // let upUrl = response.data.urlStr

  // editor.customConfig.uploadImgServer = response.data.urlStr
  // editor.customConfig.uploadImgParams = response.data.postObject
  // editor.customConfig.uploadImgHeaders = {
  //   'accessToken': 'eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI0MDYwMDQwIiwiaWF0IjoxNTgyNjMyNTY2LCJzdWIiOiJkc2tqMiIsImlzcyI6ImRza2oxIiwiZXhwIjoxNjE0MTY4NTY2fQ.CCcMQvNetTESB-hnHBJgQEreO8sya-1I8L91v4TJxcA'
  // }
  // console.log(el);
  el && (el.innerText = '上传中')
  // console.dir(el);
  let base641 = base64
  return new Promise((resolve, refuse) => {
    ajax({
      withCredentials: false,
      file: base64,
      // data,
      filename: 'file',
      action: '/cms/commons/UploadFile',
      onProgress: e => {
      if(progress){ progress.innerText ='上传进度：' +(e.percent || 0) + '%'}
        console.log(progress,e);
        // console.log(e);
      },
      onSuccess: res => {
        console.log(res);
        el && (el.innerText = '上传成功')
        if(progress){progress.innerText = '上传成功'}
        resolve(res.Url)
      },
      onError: (err, response) => {
        alert('上传失败！')
        if(progress){progress.innerText = '上传失败'}
        el && (el.innerText = '上传失败')
        resolve(false)
      }
    })
  })
}

function getImg(url,el){

  return new Promise((resolve, reject) => {
    $.ajax({
      url:'/cms/commons/UploadFileByUrl?url='+url,
      type: "post",
      success: function (res) {
        let url = Object.prototype.toString.call(res) === '[object Object]' && res.Url
        resolve(url)
      },
      error: function(XMLHttpRequest, textStatus, errorThrown) {
        resolve(false)
      }
    })
  })
}

// 获取DOM附近相邻的元素
function siblings(elm) {
  let arr = [];
  let siblingsArr = elm.parentNode.children;

  for (let item of siblingsArr) {
    if (item !== elm) {
      arr.push(item)
    }
  }

  return arr
}

// 处理是否激活class
function disposeActive(elm) {
  elm.classList.add("active");

  siblings(elm).forEach(function (item) {
    item.classList.remove('active')
  })
}

function returnCropperBlob() {
  return new Promise((resolve, reject) => {
    cropper.getCroppedCanvas().toBlob(function (blob) {
      resolve(blob)
    })
  })
}

function upBtn(str) {
 let btn = document.getElementById(str+'Btn')
  // console.log(str);
 if(!btn) return
  btn.onclick = function(e){
    e.preventDefault()
    document.getElementById('file-up').click()
    document.querySelector('.pop-up-model').style.display = "flex"
    openActionBtn(str,btn)
  }
}


function openActionBtn(tap,el) {
  switch (tap) {
    case '本地上传' :
      document.getElementById('file-up').click()
      break
  }

  document.getElementById('action-img-btn').onclick = async function (e) {
    let innerHTML = e.target.innerHTML

    switch (innerHTML) {
      case '取消' :
        // console.log(445456);
        close()
        break
      case '保存' :
        let blob = await returnCropperBlob()
        e.target.innerHTML = '上传中'
        let res = await updateImg(blob,el)

        switch (tap) {
          case '本地上传' :
            let img = `<img src="${res}"> `
            // console.log(img);
            editor.cmd.do('insertHTML', matchImg(img))
            break

          case 'TitleImageUrl' :
            upImg(tap,res)
            break
          case 'ImageUrl' :
            // console.log(ImageUrl);
            upImg(tap,res)
            break
          case 'TitleImageUrl1':
              upImg(tap, res)
              break
          case 'TitleImageUrl2':
              upImg(tap, res)
              break
          case 'TitleImageUrl3':
              upImg(tap, res)
              break
          case 'BannerUrl' :
            // console.log(ImageUrl);
            upImg(tap,res)
            break

          default :
            // console.log(res);
            if(!res){
              // console.log(activeImg);
            }else{
              activeImg.src = res
            }
            clickImg()
            close()
            break
        }
        e.target.innerHTML = '保存'
        document.querySelector('.pop-up-model').style.display = "none"
        break
    }
  }
}

function upImg(name,res) {
  // console.log(name);
  document.getElementById(name).value = res
  document.getElementById(name+'Img').src = res
}

function close() {
  document.querySelector('.pop-up-model').style.display = "none"
}

var _toString = Object.prototype.toString;
function toRawType(value) {
  return _toString.call(value).slice(8, -1)
}
